import {Product,CarProduct} from '../types/products'

interface IState{
    list:Product[],
    carList:CarProduct[],
    checkAll:boolean,
    total:number,  
}
//初始化数据
let initData:IState = {
    list:[],
    carList:[],
    checkAll:false,
    total:0 
}

//获取index

function getIndex(data:CarProduct[],id:number):number{
    return data.findIndex((item:CarProduct) => item.id === id)
}

//计算总价
function totalMoney(data:CarProduct[]):number{
    console.log(data);
    return data.reduce((pre,cur) => {
        return pre += cur.checked ? cur.num*cur.price : 0;
    },0)
}

export default (state=initData,action:any) => {
    switch (action.type) {
        case 'INIT_LIST':
            return {...state,list:[...action.list]}
        case 'ADD_PRO':{
            let index = getIndex(state.carList,action.pro.id);
            if(index != -1){
                //2.不是第一次添加
                state.carList[index].num++;
            }else{
                //1.第一次添加  
                action.pro.num = 1;
                action.pro.checked = true;
                state.carList.push(action.pro);
                state.checkAll = state.carList.every(item => item.checked);
            }
            state.total = totalMoney(state.carList);
            return {...state,carList:[...state.carList]}
        }
        case 'CHANGE_NUM':{
            //id num
            let index = getIndex(state.carList,action.id);
            let target = state.carList[index];
            target.num = action.num;
            state.carList[index] = {...target};
            state.total = totalMoney(state.carList);
            return {...state,carList:[...state.carList]}
        }
        case 'CHANGE_CHECK':{
            let index = getIndex(state.carList,action.id);
            let target = state.carList[index];
            target.checked = action.checked;
            state.carList[index] = {...target};
            state.checkAll = state.carList.every(item => item.checked);
            state.total = totalMoney(state.carList);
            return {...state,carList:[...state.carList]}
        }
        case 'CHANGE_ALL':{
            state.checkAll = action.checkAll
            state.carList = state.carList.map(item => {
                item.checked = action.checkAll;
                return {...item}
            })
            state.total = totalMoney(state.carList);
            return {...state,carList:[...state.carList]}
        }
        default:
            return state;
    }
}